<template>
  <div :class="computedTreeClass + ' computedTree'" :key="updateInstruction+'computedTree'">
    <template v-if="filterShow">
      <valueTree
        :fieldArr="fieldArr"
        :filter="filter"
        :limit="limit"
        :del="del"
        :delIcon="delIcon"
        :add="add"
        :addIcon="addIcon"
        :deep="deep"
        :deepIcon="deepIcon"
        :groupWrite="groupWrite"
        :groupWriteIcon="groupWriteIcon"
      ></valueTree>
    </template>
  </div>
</template>

<script>
import valueTree from "./valueTree.vue";

export default {
  name: "computedTree",
  components: { valueTree },
  props: {
    fieldArr: {
      type: Array,
      default: () => {
        return [];
      }
    }, // 第一列可选值
    computedTreeClass: {
      type: String,
      default: "computedTree"
    }, // 计算盒子类名
    filterEnter: {
      default: null
    },
    limit: {
      type: Number,
      default: 2
    }, // 限制当前等级
    del: {
      default: false
    }, // 删除回退功能
    delIcon: {
      type: String,
      default: "el-icon-close"
    }, // 删除图标
    add: {
      default: "并且满足"
    }, // 追加功能
    addIcon: {
      type: String,
      default: "el-icon-plus"
    }, // 追加图标
    deep: {
      default: false
    }, // 层次功能
    deepIcon: {
      default: false
    }, // 层次图标
    groupWrite: {
      default: "批量录入"
    }, // 批量录入
    groupWriteIcon: {
      type: String,
      default: "el-icon-notebook-1"
    } // 批量录入图标
  },
  data: function() {
    return {
      filter: null,
      uniqueIdentificationOnly: 1, // 用来生成唯一标识的变量
      updateInstruction: 0 // 组件更新变量
    };
  },
  methods: {
    // 最外层的 初始化 、 同层追加函数
    initAdd() {
      let obj = null;
      if (!this.filter) {
        obj = {
          render_index: 1,
          filters: [],
          relation: "AND",
          conditions: [
            {
              render_index: 2,
              field: "",
              function: "",
              params: []
            }
          ]
        };
      } else {
        let _render_index = this.getMaxSort() + 1;
        try {
          obj = JSON.parse(JSON.stringify(this.filter));
          obj.conditions.push({
            render_index: _render_index,
            field: "",
            function: "",
            params: []
          });
        } catch (err) {
          console.log(err, "错误");
        }
      }
      obj = this.dataCompletion(obj);
      console.log(obj,'筛选')
      this.filter = obj;
    },

    // 获取当前最大排序记录
    getMaxSort(obj = this.filter, sortName = "render_index", maxNum = 0) {
      let maxNumber = parseInt(Number(maxNum));
      let that = this;
      if (!Object.prototype.toString.call(obj) === "[object Object]" || !obj) {
        return maxNumber;
      }
      Object.keys(obj).forEach(function(key) {
        if (key === sortName) {
          maxNumber =
            maxNumber > parseInt(Number(obj[key]))
              ? maxNumber
              : parseInt(Number(obj[key]));
        }
        if (Array.isArray(obj[key])) {
          for (let i = 0; i <= obj[key].length - 1; i++) {
            maxNumber = that.getMaxSort(
              JSON.parse(JSON.stringify(obj[key][i])),
              sortName,
              maxNumber
            );
          }
        }
      });
      return maxNumber;
    },

    // 为数据 补全 等级 和   唯一标识
    dataCompletion(
      obj = this.filter, // 进行补全的数据
      idName = "uniqueIdentification", // 标识符名称
      gradeName = "grade", // 层级名称
      gradeValue = 0, // 当前层级
      renderIndex = "render_index" // 渲染关键字
    ) {
      let that = this;
      if (!Object.prototype.toString.call(obj) === "[object Object]" || !obj) {
        return obj;
      }
      let _obj = {};
      let bool = false; // 唯一标识判断符号
      let bool_g = false; // 层级判断符号
      try {
        // 排序关键字追加
        if (!obj[renderIndex]) {
          obj[renderIndex] = parseInt(Number(that.getMaxSort() + 1));
        }

        Object.keys(obj).forEach(function(key) {
          if (key === idName) {
            bool = true;
          }
          if (key === gradeName) {
            bool_g = true;
          }

          if (Array.isArray(obj.filters)) {
            for (let i = 0; i <= obj.filters.length - 1; i++) {
              let num = obj[gradeName] ? obj[gradeName] : gradeValue + 1;
              obj.filters[i] = that.dataCompletion(
                obj.filters[i],
                idName,
                gradeName,
                num,
                renderIndex
              );
            }
          }

          if (Array.isArray(obj.conditions)) {
            for (let i = 0; i <= obj.conditions.length - 1; i++) {
              let num = obj[gradeName] ? obj[gradeName] : gradeValue + 1;
              obj.conditions[i] = that.dataCompletion(
                obj.conditions[i],
                idName,
                gradeName,
                num,
                renderIndex
              );
            }
          }




          _obj[key] = JSON.parse(JSON.stringify(obj[key]));
        });
        if (!bool) {
          let _idName = Math.random() * 10 + 1;
          _obj[idName] = this.uniqueIdentificationOnly + _idName;
          this.uniqueIdentificationOnly += _idName;
        }
        if (!bool_g) {
          _obj[gradeName] = parseInt(Number(gradeValue + 1));
        }
      } catch (err) {
        console.log(err, "错误");
      }
      return _obj;
    },

    // 节点更改
    // 参数一:层级 参数二:标识 参数三:处理方式  参数四:父对象   参数五:节点在父对象中的下标
    valueTreeChange(
      grade,
      uniqueIdentification,
      type,
      newValue,
      obj = this.filter,
      parent = {},
      index = null
    ) {
      let that = this;

      // filters 移除函数
      function filtersRemove(filter) {
        let _filter = JSON.parse(JSON.stringify(filter));
        for (let i = 0; i <= _filter.filters.length - 1; i++) {
          if (!_filter.filters[i].relation) {
            let changeOBJ = _filter.filters[i];
            _filter.conditions.push(changeOBJ);
            _filter.filters.splice(i, 1);
            i--;
          } else {
            _filter.filters[i] = filtersRemove(_filter.filters[i]);
          }
        }
        return _filter;
      }

      // 处理节点退化到临界点的函数
      function nodeDegradation(filter) {
        let _filter = JSON.parse(JSON.stringify(filter));
        try {
          if (
            _filter &&
            _filter.conditions &&
            _filter.filters &&
            _filter.relation
          ) {
            let len = _filter.conditions.length + _filter.filters.length;
            if (len == 1) {
              let _render_index = _filter.render_index;
              let arrONE = _filter.conditions[0]
                ? _filter.conditions[0]
                : _filter.filters[0];
              arrONE.render_index = _render_index;
              _filter = gradeRise(arrONE);
            }
            if (len > 1) {
              for (let i = 0; i <= _filter.conditions.length - 1; i++) {
                _filter.conditions[i] = nodeDegradation(_filter.conditions[i]);
              }
              for (let i = 0; i <= _filter.filters.length - 1; i++) {
                _filter.filters[i] = nodeDegradation(_filter.filters[i]);
              }
            }
          }
        } catch (err) {
          console.log(err, "错误");
        }
        return _filter;
      }

      // 层级上升函数
      function gradeRise(obj, gradeName = "grade") {
        if (
          !Object.prototype.toString.call(obj) === "[object Object]" ||
          !obj
        ) {
          return obj;
        }
        try {
          Object.keys(obj).forEach(key => {
            if (key == gradeName) {
              obj[gradeName]--;
              obj[gradeName] = obj[gradeName] < 1 ? 1 : obj[gradeName];
            }
            if (Array.isArray(obj[key])) {
              for (let i = 0; i <= obj[key].length - 1; i++) {
                obj[key][i] = gradeRise(obj[key][i]);
              }
            }
          });
        } catch (err) {
          console.log(err, "错误");
        }
        return obj;
      }

      // 新值更改
      function newValueSet(obj, newValue) {
        if (
          !Object.prototype.toString.call(obj) === "[object Object]" ||
          !obj
        ) {
          return obj;
        }
        let _obj = JSON.parse(JSON.stringify(obj));
        try {
          Object.keys(_obj).forEach(() => {
            if (_obj.uniqueIdentification == newValue.uniqueIdentification) {
              _obj = newValue;
            }
            if (Array.isArray(_obj.filters)) {
              for (let i = 0; i <= _obj.filters.length - 1; i++) {
                _obj.filters[i] = newValueSet(obj.filters[i], newValue);
              }
            }
            if (Array.isArray(_obj.conditions)) {
              for (let i = 0; i <= _obj.conditions.length - 1; i++) {
                _obj.conditions[i] = newValueSet(obj.conditions[i], newValue);
              }
            }
          });
        } catch (err) {
          console.log(err, "错误");
        }
        return _obj;
      }

      try {
        // 判断标识符是否相等
        Object.keys(obj).forEach(key => {
          if (obj[key] == uniqueIdentification) {
            let temporaryGRADE = obj.grade ? obj.grade : 2;
            let backLength;
            let backObj;
            let temporaryOBJ = {
              render_index: that.getMaxSort() + 1,
              field: "",
              grade: temporaryGRADE,
              function: "",
              params: []
            };

            temporaryOBJ = that.dataCompletion(temporaryOBJ); // 临时对象，用来补足数据
            switch (type) {
              case "del":
                parent.conditions.splice(index, 1);
                backLength = parent.conditions.length + parent.filters.length;
                if (backLength == 1) {
                  backObj = filtersRemove(nodeDegradation(that.filter));
                  if (!backObj.relation) {
                    that.filter = that.dataCompletion({
                      render_index: 1,
                      filters: [],
                      relation: "AND",
                      conditions: [backObj]
                    });
                  } else {
                    that.filter = backObj;
                  }
                  return;
                }
                if (backLength == 0) {
                  that.filter = null;
                  console.log("全部删除");
                }
                break;
              case "add":
                if (
                  parent &&
                  parent.conditions &&
                  Array.isArray(parent.conditions)
                ) {
                  parent.conditions.push(temporaryOBJ);
                } else {
                  that.initAdd();
                }
                break;
              case "deep":
                if (parent) {
                  if (!parent.conditions || !Array.isArray(parent.conditions)) {
                    parent.conditions = [];
                  }
                  if (!parent.filters || !Array.isArray(parent.filters)) {
                    parent.filters = [];
                  }
                  let len = parent.conditions.length + parent.filters.length;
                  if (len < 2) {
                    parent.conditions.push(temporaryOBJ);
                  } else {
                    obj.grade++;
                    temporaryOBJ.grade++;
                    parent.filters.push(
                      that.dataCompletion({
                        relation: "AND",
                        filters: [],
                        render_index: obj.render_index
                          ? obj.render_index
                          : that.getMaxSort() + 1,
                        grade: temporaryGRADE,
                        conditions: [obj, temporaryOBJ]
                      })
                    );
                    parent.conditions.splice(index, 1);
                  }
                } else {
                  if (!obj.conditions || !Array.isArray(obj.conditions)) {
                    obj.conditions = [];
                  }
                  if (!obj.filters || !Array.isArray(obj.filters)) {
                    obj.filters = [];
                  }
                  let len = obj.conditions.length + obj.filters.length;
                  if (len < 2) {
                    obj.conditions.push(temporaryOBJ);
                  } else {
                    obj.grade++;
                    temporaryOBJ.grade++;
                    obj.filters.push(
                      that.dataCompletion({
                        relation: "AND",
                        filters: [],
                        render_index: obj.render_index
                          ? obj.render_index
                          : that.getMaxSort() + 1,
                        grade: temporaryGRADE,
                        conditions: [obj, temporaryOBJ]
                      })
                    );
                    obj.conditions.splice(index, 1);
                  }
                }
                break;
              case "value":
                that.filter = JSON.parse(
                  JSON.stringify(newValueSet(that.filter, newValue))
                );
                break;
              case "relation":
                obj.relation = newValue;
                break;
              default:
                break;
            }
            return;
          }
          if (Array.isArray(obj[key])) {
            obj[key].map((_i, _in) => {
              that.valueTreeChange(
                grade,
                uniqueIdentification,
                type,
                newValue,
                _i,
                obj,
                _in
              );
            });
          }
        });
      } catch (err) {
        console.log(err, "错误");
      }
    }
  },
  watch: {
    filter: {
      handler(newValue) {
        this.updateInstruction++;
        this.$emit("change", newValue);
      },
      deep: true
    }
  },
  computed: {
    filterShow() {
      let bool = false;
      try {
        if (
          this.filter &&
          this.filter.filters &&
          this.filter.filters.length &&
          this.filter.filters.length > 0
        ) {
          bool = true;
        }
        if (
          this.filter &&
          this.filter.conditions &&
          this.filter.conditions.length &&
          this.filter.conditions.length > 0
        ) {
          bool = true;
        }
      } catch (err) {
        console.log(err, "错误");
      }
      return bool;
    }
  },
  beforeCreate() {},
  created() {
    this.filter = JSON.parse(JSON.stringify(this.filterEnter));
  },
  beforeMount() {
    //  为数据补全  标识符   和   层级
    this.filter = this.dataCompletion();
    this.updateInstruction++;
  },
  mounted() {}
};
</script>

<style scoped lang='scss'>
// .computedTree:hover {
//   background: rgba($color: #f2f6fc, $alpha: 0.6);
// }
</style>